package ustc.running.util;

import ustc.running.R;
import android.content.Context;
import android.os.RemoteException;
import android.widget.Toast;

import com.iflytek.speech.ErrorCode;
import com.iflytek.speech.ISpeechModule;
import com.iflytek.speech.InitListener;
import com.iflytek.speech.SpeechConstant;
import com.iflytek.speech.SpeechSynthesizer;
import com.iflytek.speech.SpeechUtility;
import com.iflytek.speech.SynthesizerListener;

/**
 * Tts 语音播放
 * 
 * @author honest
 * 
 */
public class TtsPlayer {
	// 语音合成对象
	private SpeechSynthesizer mTts;
	private boolean TtsFlag = true;
	private Context context = null;

	public TtsPlayer(Context context) {
		this.context = context;
		mTts = new SpeechSynthesizer(context, mTtsInitListener);
		initEngineType();
	}

	/**
	 * 初始化语音 根据是否存在本地TTS引擎
	 */
	private void initEngineType() {
		if (SpeechUtility.getUtility(context).queryAvailableEngines() == null
				|| SpeechUtility.getUtility(context).queryAvailableEngines().length <= 0
				|| !TtsFlag) {
			stop();
			Toast.makeText(context, context.getResources()
					.getString(R.string.no_tts_engine), Toast.LENGTH_LONG).show();
			return ;
		}
		mTts.setParameter(SpeechConstant.ENGINE_TYPE, "local");
		mTts.setParameter(SpeechSynthesizer.VOICE_NAME, "xiaoyan");
		mTts.setParameter(SpeechSynthesizer.SPEED, "50");
		mTts.setParameter(SpeechSynthesizer.PITCH, "50");
		mTts.setParameter(SpeechConstant.PARAMS,
				"tts_audio_path=/sdcard/tts.pcm");
	}

	/**
	 * 播放
	 * 
	 * @param text
	 */
	public void play(final String text) {
		mTts.startSpeaking(text, mTtsListener);
	}

	private InitListener mTtsInitListener = new InitListener() {

		@Override
		public void onInit(ISpeechModule arg0, int code) {
			if (code != ErrorCode.SUCCESS) {
				TtsFlag = false;
			}
		}
	};

	/**
	 * 合成回调监听
	 */
	private SynthesizerListener mTtsListener = new SynthesizerListener.Stub() {
		@Override
		public void onBufferProgress(int progress) throws RemoteException {
		}

		@Override
		public void onCompleted(int code) throws RemoteException {
		}

		@Override
		public void onSpeakBegin() throws RemoteException {
		}

		@Override
		public void onSpeakPaused() throws RemoteException {
		}

		@Override
		public void onSpeakProgress(int progress) throws RemoteException {
		}

		@Override
		public void onSpeakResumed() throws RemoteException {
		}
	};

	/**
	 * 释放资源
	 */
	public void stop() {
		mTts.stopSpeaking(mTtsListener);
		// 退出时释放连接
		mTts.destory();
	}

}
